<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/16
 * Time: 21:00
 */
namespace Pay\Controller;

use Common\Common\Api\Order;
use Common\Common\Api\Ordermember;
use Common\Common\Api\Redis\Channel;
use Common\Common\Api\Redis\Product;

/**
 * Class ManyiController
 * @package Pay\Controller
 * 小祝 ajie
 */
class XiaozhuController extends PayController{
    protected $config;
    protected $class;
    public function __construct(){
        parent::__construct();
        $classes = explode("\\",__CLASS__);
        $class = end($classes);
        $this->class = substr($class, 0, stripos($class, "Controller"));
    }

    public function pay($array){
        $this->config = Channel::getInstance()->getById($array['channel']);

        if(!$this->config){
            $this->showmessage('通道错误!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $parameter = array(
            'code' => $this->config['code'], // 通道名称
            'title' => $this->config['title'],
            'exchange' => 1, // 金额比例
            'gateway' => $this->config['gateway'],
            'orderid' => createOrderId(),
            'out_trade_id' => I("request.ordNo") ? I("request.ordNo") : I("request.pay_orderid"),
            'body' => 'pay',
            'channel'=>$array
        );

        // $isMobile = isMobile();
        $return = $this->orderadd( $parameter );

        switch($this->config['paytype']){
            case 17:
            case 18:
                $pay_bankcode = 'alipay';
                break;
            default:
                $this->showmessage('暂不支持此方式!',['code'=>C("THIRDCODES.".$this->class)]);
        }


        $native = array(
            "app_id" => $this->config['mch_id'],
            "price" => strval($return['amount']) ,
            "out_order_id" => $return['orderid'],
            "type" => $pay_bankcode,
            "notifyurl" => $return['notifyurl'],
            "returnurl" => $return['callbackurl'],
            "extend" => 'wlf',
        );
    //    md5( md5( price + out_order_id + type + notifyurl + returnurl + extend ) + app_key )


        $native['sign'] =  md5( md5(   $native['price'].$native['out_order_id'].$native['type'].$native['notifyurl'].$native['returnurl'].$native['extend']) . $this->config['signkey']);


        $res  = curl_get2($this->config['gateway'], $native);
        $resp = json_decode($res, true);

       // var_dump('<pre/>',$native,$this->config['gateway'],$res,$resp);exit();

        /**
        array(5) {
        ["code"]=>
        int(1)
        ["msg"]=>
        string(18) "创建订单成功"
        ["data"]=>
        array(15) {
        ["out_order_id"]=>
        string(19) "sn20190716160752382"
        ["no"]=>
        string(28) "2019071504200340001040880575"
        ["price"]=>
        string(7) "2000.00"
        ["pay_price"]=>
        string(4) "0.00"
        ["extend"]=>
        string(3) "wlf"
        ["type"]=>
        string(6) "alipay"
        ["discountprice"]=>
        string(7) "2000.00"
        ["remainseconds"]=>
        int(480)
        ["status"]=>
        string(10) "inprogress"
        ["remark"]=>
        string(28) "2019071504200340001040880575"
        ["manual"]=>
        bool(true)
        ["returnurl"]=>
        string(142) "http://callback.wanglianfu.com/Pay_Xiaozhu_callbackurl.html?order_id=15&out_order_id=sn20190716160752382&sign=c031452d08f784cb95d7764bd43153c9"
        ["qrcodeurl"]=>
        string(191) "https://qr.alipay.com/_d?_b=peerpay&enableWK=YES&biz_no=2019071504200340001040880575_634e61c166f71f063c969ad12d265f3e&app_name=tb&sc=qr_code&v=20190722&sign=aaf8ff&__webview_options__=pd%3dNO"
        ["queryurl"]=>
        string(113) "http://wy.cnzhifu.top/addons/pay/api/query?out_order_id=sn20190716160752382&sign=0d8459a32198e3c4abb5a5fa86c24eda"
        ["h5url"]=>
        string(191) "https://qr.alipay.com/_d?_b=peerpay&enableWK=YES&biz_no=2019071504200340001040880575_634e61c166f71f063c969ad12d265f3e&app_name=tb&sc=qr_code&v=20190722&sign=aaf8ff&__webview_options__=pd%3dNO"
        }
        ["url"]=>
        string(0) ""
        ["wait"]=>
        int(3)
        }
         */


        $code = $resp["data"]['qrcodeurl'];
        if(!$code){
            if($res['msg']){
                $this->showmessage($res['msg'],['code'=>C("THIRDCODES.".$this->class)]);
            }
            $this->showmessage('获取支付连接失败！',['code'=>C("THIRDCODES.".$this->class)]);
        }

        //当上游通道传回来的是 二维码图片时

        $paytype = transArr( C("PAYTYPES"), "id");
        $this->assign("wap_url", $code);
         //$this->assign("code_url", $res['data']['payurl']);
        $this->assign("title", $paytype[$this->config['paytype']]);
        $this->assign("return", $return);
        $this->assign("imgurl", C("website.DOMAIN")."/Pay_Qrcode_getCode?type=2&data=" . base64_encode($code));
        //选择支付页面
        switch($this->config['paytype']){

            //支付宝扫码
            case 3:
                //支付宝H5
            case 4:
            case 17:
            case 18:
                 $this->display("WeiXin/alipay");
                break;
            default:
                $this->display("WeiXin/Pay");//收银台
        }

        exit();
    }



    //通知
    public function notifyurl(){
       // $this->debug_callback();

        //IP白名单
        if(!$this->checkip(getIP(),['47.75.45.29'])){
            exit("wrong");
        }

        $p = I("post.");


        if(!$p || empty($p)){
            exit("wrong");
        }

        //获取订单信息
        $orderid = $p['out_order_id'];

        //获取订单
        $find = $this->checkOrderNotify($orderid);
        if(!$find){
            echo 'order_not_found'; exit;
        }

        //保存回调数据
        M("Order")->where(array("pay_orderid"=>$orderid))->save(array(
            "pay_orderid_rd"=> 0
        ));


        $real_amount =  $p['price'];     //实际支付金额
        $pay_amount =  $find['pay_amount']; //商户提交订单金额

        if(abs($real_amount - $pay_amount) > 0.1){
            echo 'wrong_money'; exit;
        }

        //获取渠道信息
        $this->config = Channel::getInstance()->find(['code'=>$this->class]);

        $sign = $p['sign'];
        unset($p['sign']);

        //md5(md5(out_order_id + price + type + paytime + extend)+app_key)

        $sign2  = md5(md5($p['out_order_id'].$p['price'] .$p['type'] .$p['paytime'].$p['extend'] ).$this->config['signkey']);

        if($sign !== $sign2){
            exit("sign_wrong");
        }

        if($p['extend'] !== 'wlf'){
            exit("pay_fail");
        }

        $this->async($find['pay_orderid'],"success");
    }

    public function callBackUrl(){

        echo '处理成功'; exit;
    }
}
